//
//  ReactorKitTest1ViewController.swift
//  iOS-RxSwift-Tutorials_Example
//
//  Created by mengru.tian on 2020/9/24.
//  Copyright © 2020 CocoaPods. All rights reserved.
//

import UIKit
import RxSwift
import ReactorKit

final class ViewReactor: Reactor {
    //代表用户行为
    enum Action {
        case increase //加一操作
        case decrease //减一操作
    }
     
    //代表状态变化
    enum Mutation {
        case increaseValue //数字加一
        case decreaseValue //数字减一
        case setLoading(Bool) //设置加载状态
    }
     
    //代表页面状态
    struct State {
        var value: Int //当前数字
        var isLoading: Bool  //当前加载状态
    }
     
    //初始页面状态
    let initialState: State
     
    init() {
        self.initialState = State(
            value: 0, //数字默认为0
            isLoading: false  //默认加载状态为false
        )
    }
     
    //实现 Action -> Mutation 的转换
    func mutate(action: Action) -> Observable<Mutation> {
        switch action {
        case .increase:
            //如果当前正在加载中则不继续
            guard !self.currentState.isLoading else { return Observable.empty() }
            //依次执行下面三个状态变化动作
            return Observable.concat([
                Observable.just(Mutation.setLoading(true)),
                Observable.just(Mutation.increaseValue)
                    .delay(1, scheduler: MainScheduler.instance), //数字改变延迟1秒钟
                Observable.just(Mutation.setLoading(false)),
                ])
             
        case .decrease:
            //如果当前正在加载中则不继续
            guard !self.currentState.isLoading else { return Observable.empty() }
            //依次执行下面三个状态变化动作
            return Observable.concat([
                Observable.just(Mutation.setLoading(true)),
                Observable.just(Mutation.decreaseValue)
                    .delay(1, scheduler: MainScheduler.instance),  //数字改变延迟1秒钟
                Observable.just(Mutation.setLoading(false)),
                ])
        }
    }
     
    //实现 Mutation -> State 的转换
    func reduce(state: State, mutation: Mutation) -> State {
        //从旧状态那里复制一个新状态
        var state = state
         
        //根据状态变化设置响应的状态值
        switch mutation {
        case .increaseValue:
            state.value += 1
             
        case .decreaseValue:
            state.value -= 1
             
        case let .setLoading(isLoading):
            state.isLoading = isLoading
        }
         
        //返回新状态
        return state
    }
}

class ReactorKitTest1ViewController: UIViewController, StoryboardView {
    
    typealias Reactor = ViewReactor
    
    var reactor: ViewReactor?
    
    @IBOutlet weak var label: UILabel!  //显示数字的文本标签
    @IBOutlet weak var minus: UIButton! //减一按钮
    @IBOutlet weak var plus: UIButton! //加一按钮
    @IBOutlet weak var activityIndicator: UIActivityIndicatorView!  //活动指示器
     
    var disposeBag = DisposeBag()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        title = "65.ReactorKit架构1：安装配置、基本用法"
        view.backgroundColor = .white
        
        //设置reactor，会自动触发bind()方法
        self.reactor = ViewReactor()
    }
    
    func bind(reactor: ViewReactor) {
        //Action（实现 View -> Reactor 的绑定）
        plus.rx.tap  //按钮点击事件
            .map { Reactor.Action.increase }  //转换为 Action.increase
            .bind(to: reactor.action)  //绑定到 reactor.action
            .disposed(by: disposeBag)
         
        minus.rx.tap  //按钮点击事件
            .map { Reactor.Action.decrease }  //转换为 Action.increase
            .bind(to: reactor.action)  //绑定到 reactor.action
            .disposed(by: disposeBag)
         
        // State（实现 Reactor -> View 的绑定）
        reactor.state.map { $0.value }  //得到最新数字值
            .distinctUntilChanged()
            .map { "\($0)" }   //装成字符串
            .bind(to: label.rx.text)  //绑定到文本标签上
            .disposed(by: disposeBag)
         
        reactor.state.map { $0.isLoading } //活动指示器的绑定
            .distinctUntilChanged()
            .bind(to: activityIndicator.rx.isAnimating)
            .disposed(by: disposeBag)
    }

}
